package bhwz.seac3.db.nbadata;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.hibernate.Query;
import org.hibernate.SQLQuery;

import bhwz.seac3.db.Database;
import bhwz.seac3.dbservice.nbadata.PlayerMatchDBService;
import bhwz.seac3.dbservice.nbadata.SaveQueryDBService;
import bhwz.seac3.po.MatchPo;
import bhwz.seac3.po.PlayerPo;

public class PlayerMatchDB implements PlayerMatchDBService {
	private SaveQueryDBService<PlayerMatchesEntity> mapdb;
	private SaveQueryDBService<MatchPo> matchdb;
	
	public PlayerMatchDB(SaveQueryDBService<PlayerMatchesEntity> mapdb,SaveQueryDBService<MatchPo> matchdb){
		this.mapdb=mapdb;
		this.matchdb=matchdb;
	}

	@Override
	public void addMatchToPlayer(MatchPo match, PlayerPo player)
			throws Exception {
		if(match==null||player==null||match.getId()==null||player.getId()==null){
			return;
		}
		PlayerMatchesEntity queryId=new PlayerMatchesEntity();
		queryId.setPlayerId(player.getId());
		
		PlayerMatchesEntity entity=mapdb.queryById(queryId);
		if(entity==null||!entity.getPlayerId().equals(queryId.getId())){
			entity=queryId;
		}
		//hibernate监视的对象不能直接更改，需要先制作一份clone
		PlayerMatchesEntity newEntity=new PlayerMatchesEntity();
		newEntity.setPlayerId(entity.getPlayerId());
		newEntity.setMatchesId(new ArrayList<>(entity.getMatchesId()));
		newEntity.getMatchesId().add(match.getId());
		mapdb.updateById(newEntity);
	}

	@Override
	public List<MatchPo> getPlayerMatchList(String playerName, String season)
			throws Exception {
		PlayerMatchesEntity queryId=new PlayerMatchesEntity();
		queryId.setPlayerId(playerName);
		
		PlayerMatchesEntity entity=mapdb.queryById(queryId);
		if(entity==null)
			return null;
		List<MatchPo> result= entity.getMatchesId().stream().map(id->{
			MatchPo qid=new MatchPo();
			qid.setId(id);
			try {
				return matchdb.queryById(qid);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}).filter(po->season==null?true:po.getSeason().equals(season)).collect(Collectors.toList());
		result.sort((m1,m2)->(m2.getDate()-m1.getDate())>0?1:-1);
		return result;
	}
	
	@SuppressWarnings("unused")
	private List<MatchPo> getPlayerMatchListOldSlowWay(String playerName, String season)
			throws Exception {
		/*
		 * 实现方式： 1:在PlayerScoreTable表中select出所有球员姓名等于playerName的比分表
		 * 2:在MatchPo_Team1PlayersScore
		 * ,MatchPo_Team2PlayersScore的Match和PlayerScoreTable的主键映射表中
		 * ，查询对应的成绩表的比赛的key 3:通过得到的比赛key查询比赛
		 */
		List<MatchPo> result = new ArrayList<>();
		Database.executeTransaction(s -> {
			Query queryPlayerScoreTable = s
					.createQuery("select po.id from PlayerScoreTablePo po where po.球员名=?");
			queryPlayerScoreTable.setString(0, playerName);
			for (Object o : queryPlayerScoreTable.list()) {
				long scoreTableId = (long) o;
				SQLQuery queryMatchesAsTeam1 = s
						.createSQLQuery("select id from MatchPo_Team1PlayersScore  where elt=?");
				SQLQuery queryMatchesAsTeam2 = s
						.createSQLQuery("select id from MatchPo_Team2PlayersScore  where elt=?");
				queryMatchesAsTeam1.setLong(0, scoreTableId);
				queryMatchesAsTeam2.setLong(0, scoreTableId);
				List<String> matchesId = new ArrayList<>();
				for (Object oMatchId : queryMatchesAsTeam1.list()) {
					matchesId.add((String) oMatchId);
				}
				for (Object oMatchId : queryMatchesAsTeam2.list()) {
					matchesId.add((String) oMatchId);
				}
				for (String matchId : matchesId) {
					result.add((MatchPo) s.get(MatchPo.class, matchId));
				}
			}
		});
		// 过滤赛季
		List<MatchPo> rightSeasonResult = result.parallelStream()
				.filter(match -> {
					if (match.getSeason() != null)
						return match.getSeason().equals(season);
					else
						return true;
				}).collect(Collectors.toList());
		return rightSeasonResult;
	}

}
